from app.Pojo.BThing import BThing
from app.db import db


class ThingMapper:
    def __init__(self, db):
        self.db = db

    def list_things(self, page, page_size):
        """分页查询商品"""
        query = BThing.query
        total = query.count()
        things = query.order_by(BThing.create_time.desc()) \
            .limit(page_size) \
            .offset((page - 1) * page_size) \
            .all()
        return things, total

    def get_thing(self, id):
        """根据id查询商品"""
        return BThing.query.get(id)

    def save_thing(self, thing):
        """保存商品"""
        self.db.session.add(thing)
        self.db.session.commit()

    def delete_thing(self, id):
        """删除商品"""
        thing = BThing.query.get(id)
        if thing:
            self.db.session.delete(thing)
            self.db.session.commit()

    def search_things(self, title):
        """根据title模糊查询商品"""
        if not title:
            return []

        return BThing.query.filter(BThing.title.like(f'%{title}%')).all()

    def batch_delete(self, ids):
        """批量删除商品"""
        BThing.query.filter(BThing.id.in_(ids)).delete(synchronize_session=False)
        self.db.session.commit()